package org.budo.dubbo.protocol.http.dispatcher.cometd;

import org.budo.dubbo.protocol.http.dispatcher.BudoHttpDispatcherUtil;
import org.budo.dubbo.protocol.http.invocation.adapter.ProtocolResponse;
import org.cometd.bayeux.server.ServerChannel;
import org.cometd.bayeux.server.ServerMessage.Mutable;
import org.cometd.bayeux.server.ServerSession;
import org.cometd.server.BayeuxServerImpl;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;

/**
 * @author lmw
 */
public class ServerChannelMessageListener implements ServerChannel.MessageListener {
    private static final Logger log = LoggerFactory.getLogger(ServerChannelMessageListener.class);

    private BudoBayeuxServerFactoryBean budoBayeuxServerFactoryBean;

    public ServerChannelMessageListener(BudoBayeuxServerFactoryBean budoBayeuxServerFactoryBean) {
        this.budoBayeuxServerFactoryBean = budoBayeuxServerFactoryBean;
    }

    @Override
    public boolean onMessage(ServerSession serverSession, ServerChannel channel, Mutable message) {
        if (!BudoBayeuxServerFactoryBean.REQUEST_CHANNEL.equals(channel.getId())) { // 不是 request 通道
            log.info("onMessage, requestSession=" + serverSession + ", serverChannel=" + channel + ", message=" + message);
            return true;
        }

        CometdProtocolRequest protocolRequest = new CometdProtocolRequest(message);

        BayeuxServerImpl bayeuxServer = budoBayeuxServerFactoryBean.getBayeuxServer();
        ProtocolResponse protocolResponse = new CometdProtocolResponse(bayeuxServer, serverSession);

        BudoHttpDispatcherUtil.onMessage(protocolRequest, protocolResponse);
        return true;
    }
}